//
//  KeyboardViewModel.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2019/05/14.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class KeyboardViewModel {

    var keyboardHeightChange: Observable<(height: CGFloat, show: Bool)>!
    var currentKeyboardHeight: CGFloat = 0
    
    var keyboardShow: Observable<CGFloat>!
    var keyboardDismiss: Observable<CGFloat>!
    
    init() {
        let keyboardShow = NotificationCenter.default.rx
            .notification(UIResponder.keyboardWillShowNotification)
            .map{ $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
            .map{ $0 ?? CGRect.zero }
            .filter{ $0.height > 0 }
            .map{ (height: $0.height, show: true) }
        
        let keyboardHide = NotificationCenter.default.rx
            .notification(UIResponder.keyboardWillHideNotification)
            .map{ _ in (height: CGFloat(0), show: false) }
        
        self.keyboardShow = keyboardShow.map{ $0.height }
        self.keyboardDismiss = keyboardHide.map{ $0.height }
        
        keyboardHeightChange = Observable.merge(keyboardShow, keyboardHide)
            .then{ [weak self] (height, _) in
                self?.currentKeyboardHeight = height
            }.share(replay: 1)
    }
    
}
